// pages/profile/lottery/lottery.js
const app = getApp();

import {Request} from '../../../utils/request.js';
import config from '../../../utils/config.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,

    lotteryList: [],
    curPage: 1,
    totalPage: 0,
    loadingPage: false,
    lastPage: false,

    type: '',

    wxad: {}
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: (options.type == 'publish' ? '我发起的' : options.type == 'join' ? '我参与的' : '中奖纪录')
    });
    let that = this;
    that.setData({
      type: options.type,
    });

    
    if(app.callBack) {
      this.getData();
    }else {
      app.callBack = this.getData;
    }

    
  },


  getData: function() {
    this.postLotteryList();
    this.setData({
      wxad: app.globalData.wxad ?? {}
    });
  },

  // 获取列表
  postLotteryList: function() {

    
    let that = this;
    let getAnimationTime = config.ANIMATIONTIME;
    let start = Date.parse(new Date());
    let curPage = that.data.curPage;

    let param = {
      url: 'user/lottery',
      method: 'get',
      data: {
        type: that.data.type,
        page: curPage
      }
    }
    Request(param).then(function(res){

      let lotteryList = res.data.list.map(function(item) {
        item.text = item.open_type == 'bycount' ? '参与满 ' + item.open_num + ' 人, 自动开奖, 截止' + item.open_at : item.open_at + ', 自动开奖';
        let prize = [];
        item.prize.forEach(function(p) {
          prize.push(p.name + (p.type == 'money' ? '共 ' + parseFloat(p.amount) * parseFloat(p.num) + ' 元' :  p.type == 'lucky' ? '共 ' + p.amount+' 元' : ''));
        });
        item.prizeCover = item.prize[0].cover;
        item.prizeText = '奖品：' + prize.join('，');
        return item;
      });

      var data = {
        lotteryList: that.data.lotteryList.concat(lotteryList),
        curPage: res.page,
        totalPage: res.total_page,            
        display: 'block',

        loadingPage: false,
        lastPage: res.total_page == 1 || res.total_page == curPage,
      };

      that.setData(data);

    });


  },

  loadingSuccess() {
    this.setData({
      loading: true,
    })
  },

    /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    if(that.data.curPage == that.data.totalPage || that.data.loadingPage) {
      return ;
    }
    that.setData({
      curPage: that.data.curPage + 1,
      loadingPage: true,
    })
    that.postLotteryList();
  },

  onReady: function () {},
  onShow: function () {},
  onHide: function () {},
  onUnload: function () {},
  onPullDownRefresh: function () {},



})